//https://leetcode.cn/problems/minimum-number-of-days-to-make-m-bouquets/submissions/565509818/

class Solution {
public:
    int minDays(vector<int>& v, int m, int k) {
        int l = *std::min_element(begin(v), end(v)), 
            r = *std::max_element(begin(v), end(v)), 
            mid, ans = -1;
        
        auto f = [&](int x) {
            int cnt = 0;
            int r = 0;
            for (int i = 0; i < v.size(); i++) {
                if (v[i] <= x) cnt++;
                else if (cnt) cnt = 0;
                if (cnt == k) cnt = 0, r++;
            } 
            return r >= m;
        };
        while (l <= r) {
            mid = l+r>>1;
            if (f(mid)) {
                r = mid-1;
                ans = mid;
            } else l = mid+1;
        }
        return ans;
    }
};